﻿using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;

namespace CredentialsManager.ViewModels
{
    public static class Extensions
    {
        /// <summary>
        /// Returns the user name portion of a Windows user identity name
        /// </summary>
        /// <param name="login">The FQDN of the user in the format Domain\Username</param>
        public static string GetLoginName(this string login)
        {
            if (login == null)
            {
                return null;
            }

            if (login.Contains("\\"))
            {
                return login.Substring(login.IndexOf("\\") + 1);
            }
            else
            {
                return login;
            }
        }

        /// <summary>
        /// Returns the domain portion of a Windows user identity name
        /// </summary>
        /// <param name="login">The FQDN of the user in the format Domain\Username</param>
        public static string GetLoginDomain(this string login)
        {
            if (login == null)
            {
                return null;
            }

            if (login.Contains("\\"))
            {
                return login.Substring(0, login.IndexOf("\\"));
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Extension method to trim off the set_, get_ from the front of the method name for a property
        /// </summary>
        /// <param name="methodBase"></param>
        /// <returns></returns>
        public static string GetPropertyName(this MethodBase methodBase)
        {
            return methodBase.Name.Substring(4);
        }

        public static void Initialise(this BackgroundWorker backgroundWorker,
            DoWorkEventHandler doWorkHandler, 
            RunWorkerCompletedEventHandler workCompletedHandler,
            ProgressChangedEventHandler progressHandler, bool supportsCancellation)
        {
            Debug.Assert(doWorkHandler != null);
            Debug.Assert(workCompletedHandler != null);

            backgroundWorker.DoWork += doWorkHandler;
            backgroundWorker.RunWorkerCompleted += workCompletedHandler;

            if (progressHandler != null)
            {
                backgroundWorker.WorkerReportsProgress = true;
                backgroundWorker.ProgressChanged += progressHandler;
            }

            backgroundWorker.WorkerSupportsCancellation = supportsCancellation;
        }

        public static int CalculatePercentageOf(this int value, int totalItems)
        {
            if (totalItems > 0)
            {
                return (int)(((float)value / (float)totalItems) * (float)100);
            }

            return 0;
        }
    }
}
